package br.com.dev.tcc.database.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import br.com.dev.tcc.bean.Segurado;
import br.com.dev.tcc.database.DatabaseHelper;

public class SeguradoDAO {

	private final DatabaseHelper databaseHelper;

	public SeguradoDAO(DatabaseHelper databaseHelper) {
		this.databaseHelper = databaseHelper;
	}

	public int salva(Segurado segurado) {

		ContentValues values = new ContentValues();
		values.put("nome", segurado.getNome());
		values.put("cpf", segurado.getCpf());
		values.put("cnh", segurado.getCnh());
		
		SQLiteDatabase database = databaseHelper.getWritableDatabase();

		long resultado = database.insert("segurado", null, values);
		
		database.close();
		
		if (resultado == -1)
			return -1;
		else
			return getLastId();
	}

	private int getLastId() {

		SQLiteDatabase db = databaseHelper.getReadableDatabase();

		Cursor cursor = db.rawQuery("SELECT MAX(id) as id FROM segurado", null);

		int lastId = -1;

		if (cursor.moveToFirst())
			lastId = cursor.getInt(0);

		cursor.close();
		db.close();

		return lastId;
	}

	public long remover(int id) {

		SQLiteDatabase database = databaseHelper.getWritableDatabase();

		long resultado = database.delete("segurado", "id=?",
				new String[] { Integer.toString(id) });

		database.close();
		
		return resultado;
	}
}
